﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Navigation;
using MVVMFramework.View;
using SvnMonitor.FrameworkImplementation.Services;

namespace SvnMonitor.Views.Shell
{
    /// <summary>
    /// Interaction logic for ShellView.xaml
    /// </summary>
    partial class ShellView : WindowBase, IDialogService
    {
        private readonly ShellVM vm;
        private readonly MinimizeToTrayInstance minimizeToTray;

        public ShellView(ShellVM vm)
            : base(vm)
        {
            this.vm = vm;

            InitializeComponent();

            minimizeToTray = MinimizeToTray.Enable(this);
            MonitorData.Changed += monitorData_Changed;
        }

        #region IDialogService

        public bool? ShowDialog(object dialog)
        {
            if (Dispatcher.Thread != Thread.CurrentThread)
            {
                return (bool?)Dispatcher.Invoke(new Func<object, bool?>(ShowDialog), dialog);
            }

            Window window = dialog as Window;
            if (window != null)
            {
                Style windowStyle = Application.Current.Resources["WindowStyle"] as Style;

                if (windowStyle != null && window.Style == null)
                    window.Style = windowStyle;

                Window activeWindow = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
                window.Owner = activeWindow;
                return window.ShowDialog();
            }
            return null;
        }

        public void ShowFloatingWindow(object window)
        {
            ShowFloatingWindow(window, null);
        }

        public void ShowFloatingWindow(object window, Window ownerWindow)
        {
            if (Dispatcher.Thread != Thread.CurrentThread)
            {
                Dispatcher.Invoke(new Action<object>(ShowFloatingWindow), window);
            }
            else
            {
                Window showWindow = window as Window;
                if (showWindow != null)
                {
                    Style windowStyle = Application.Current.Resources["WindowStyle"] as Style;

                    if (windowStyle != null && showWindow.Style == null)
                        showWindow.Style = windowStyle;

                    showWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    showWindow.Owner = ownerWindow;
                    showWindow.ShowActivated = true;
                    showWindow.ShowInTaskbar = true;
                    showWindow.Show();
                }
            }
        }

        public void ShowFloatingWindowOnTop(object window)
        {
            Window activeWindow = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
            ShowFloatingWindow(window, activeWindow);
        }

        public void ShowMessage(string message)
        {
            ShowMessage(message, "Сообщение");
        }

        public void ShowMessage(string message, string title)
        {
            if (Application.Current.Dispatcher != null && Application.Current.Dispatcher.Thread != Thread.CurrentThread)
            {
                Application.Current.Dispatcher.Invoke(new Action<string, string>(ShowMessage), message, title);
            }
            else
            {
                Window activeWindow = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
                MessageBox.Show(activeWindow ?? this, message, title, MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        public void ShowError(string message)
        {
            ShowError(message, "Ошибка");
        }

        public void ShowError(string message, string title)
        {
            if (Application.Current.Dispatcher != null && Application.Current.Dispatcher.Thread != Thread.CurrentThread)
            {
                Application.Current.Dispatcher.Invoke(new Action<string, string>(ShowError), message, title);
            }
            else
            {
                Window activeWindow = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
                MessageBox.Show(activeWindow ?? this, message, title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void ShowWarning(string message)
        {
            ShowWarning(message, "Предупреждение");
        }

        public void ShowWarning(string message, string title)
        {
            if (Application.Current.Dispatcher != null && Application.Current.Dispatcher.Thread != Thread.CurrentThread)
            {
                Application.Current.Dispatcher.Invoke(new Action<string, string>(ShowWarning), message, title);
            }
            else
            {
                Window activeWindow = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
                MessageBox.Show(activeWindow ?? this, message, title, MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        public MessageBoxResult ShowQuestion(string message)
        {
            return ShowQuestion(message, "Вопрос");
        }

        public MessageBoxResult ShowQuestion(string message, bool showCancel)
        {
            return ShowQuestion(message, "Вопрос", showCancel);
        }

        public MessageBoxResult ShowQuestion(string message, string title)
        {
            return ShowQuestion(message, title, false);
        }

        public MessageBoxResult ShowQuestion(string message, string title, bool showCancel)
        {
            if (Dispatcher.Thread != Thread.CurrentThread)
                return (MessageBoxResult)Dispatcher.Invoke(new Func<string, string, MessageBoxResult>(ShowQuestion), message, title);

            Window activeWindow = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
            return MessageBox.Show(activeWindow ?? this, message, title, showCancel ? MessageBoxButton.YesNoCancel : MessageBoxButton.YesNo, MessageBoxImage.Question);
        }

        #endregion

        private void btnRun_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (vm.StartMonitor())
                    WindowState = WindowState.Minimized;
            }
            catch (Exception ex)
            {
                Logger.Instance.Error("An error has occurred starting Svn Monitor", ex);
                ViewManager.ShowException("An error has occurred starting Svn Monitor", ex);
            }
        }

        private void monitorData_Changed(object sender, EventArgs e)
        {
            if (Dispatcher.Thread != Thread.CurrentThread)
            {
                Dispatcher.Invoke(new EventHandler(monitorData_Changed), sender, e);
            }
            else
            {
                if (MonitorData.HasChanges())
                {
                    minimizeToTray.Text = "Some project repositories have been changed";

                    Stream iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/SvnMonitor;component/Images/ActivityChanged32.ico")).Stream;
                    minimizeToTray.Icon = new System.Drawing.Icon(iconStream);
                }
                else
                {
                    minimizeToTray.Text = Title;
                    minimizeToTray.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetEntryAssembly().Location);
                }
            }
        }

        private void openLogs_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            if (vm.OpenLogsCommand.CanExecute(null))
                vm.OpenLogsCommand.Execute(null);
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (ViewManager.ShowQuestion("Are you sure you want to exit application?", "Svn Monitor") != MessageBoxResult.Yes)
                e.Cancel = true;

            base.OnClosing(e);
        }

        private void shellView_OnLoaded(object sender, RoutedEventArgs e)
        {
            vm.RefreshLookups(true);
        }
    }
}
